package com.uniflow.security;

import com.uniflow.entity.Permission;
import com.uniflow.entity.Role;
import com.uniflow.entity.User;
import com.uniflow.mapper.UserMapper;
import com.uniflow.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 用户详情服务实现类
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    
    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private PermissionService permissionService;
    
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 根据用户名查询用户信息
        User user = userMapper.selectByUsername(username);
        if (user == null) {
            // 尝试通过邮箱查询
            user = userMapper.selectByEmail(username);
        }
        
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在: " + username);
        }
        
        // 检查用户状态
        if (user.getStatus() != 1) {
            throw new UsernameNotFoundException("用户已被禁用: " + username);
        }
        
        // 查询用户角色信息
        User userWithRoles = userMapper.selectWithRoles(user.getId());
        if (userWithRoles != null && userWithRoles.getRoles() != null) {
            user.setRoles(userWithRoles.getRoles());
        }
        
        // 构建用户权限
        Collection<GrantedAuthority> authorities = getAuthorities(user);
        
        return new CustomUserDetails(
            user.getId(),
            user.getUsername(),
            user.getPasswordHash(),
            user.getEmail(),
            user.getDisplayName(),
            user.getOrgId(),
            user.getStatus() == 1,
            true, // accountNonExpired
            true, // credentialsNonExpired
            true, // accountNonLocked
            authorities,
            user.getRoles()
        );
    }
    
    /**
     * 获取用户权限
     */
    private Collection<GrantedAuthority> getAuthorities(User user) {
        List<GrantedAuthority> authorities = new ArrayList<>();
        
        if (user.getRoles() != null) {
            for (Role role : user.getRoles()) {
                // 添加角色权限
                authorities.add(new SimpleGrantedAuthority("ROLE_" + role.getName().toUpperCase()));
            }
        }
        
        // 获取用户的所有权限（包括角色权限和特殊权限）
        List<Permission> permissions = permissionService.getUserPermissions(user.getId());
        if (permissions != null) {
            for (Permission permission : permissions) {
                authorities.add(new SimpleGrantedAuthority(permission.getCode()));
            }
        }
        
        // 如果没有任何角色，给予基础用户权限
        if (authorities.isEmpty()) {
            authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
        }
        
        return authorities;
    }
}